package com.sxpi.upload.config;

import cn.dev33.satoken.exception.NotLoginException;
import com.sxpi.common.exception.PugBusinessException;
import com.sxpi.common.exception.PugValidatorException;
import com.sxpi.common.result.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {


    /**
     * 全局异常拦截
     * 1.springmvc会把验证得错误信息放入到异常类中就是 MethodArgumentNotValidException
     *   在这个异常类中有一个：BindingResult 对象，存储了所有得验证异常信息
     * @param e
     * @return
     */
    @ResponseBody
    @ResponseStatus(HttpStatus.NOT_IMPLEMENTED)
    @ExceptionHandler
    public R handlerException(Exception e) {
        e.printStackTrace();
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e;
            return R.error(exception.getBindingResult().getFieldError().getDefaultMessage());
        } else if (e instanceof HttpRequestMethodNotSupportedException) {
            //HTTP请求类型不正确的异常
            return R.error("Web方法不支持当前的请求类型");
        } else if (e instanceof HttpMessageNotReadableException) {
            //缺少必须提交的表单数据
            return R.error("缺少提交的数据");
        } else if (e instanceof PugValidatorException) {
            //处理业务异常
            PugValidatorException exception = (PugValidatorException) e;
            return R.error(exception.getMsg());
        } else if (e instanceof PugBusinessException) {
            PugBusinessException exception = (PugBusinessException) e;
            return R.error(exception.getMsg());
        } else {
            //处理其余的异常
            return R.error("服务异常");
        }
    }


    /**
     * 捕获并处理客户端未登录或者未获取授权的异常
     * @param e
     * @return
     */
    @ResponseBody
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(NotLoginException.class)
    public R unLoginHandler(NotLoginException e) {
        return R.error(401, "会话已失效!");
    }
}
